<template>
  <el-dialog
    v-model="dialogVisible"
    :close-on-click-modal="false"
    :modal-append-to-body="false"
    :destroy-on-close="true"
    :align-center="true"
    width="80%"
    style="padding: 0 100px"
    :title="`${dialogData.title}招工信息`"
  >
    <!-- <el-scrollbar class="post-dialog-scrollbar" height="78vh">
        <section class="post-dialog-content">

        </section>
      </el-scrollbar> -->

    <el-form
      ref="jobFormRef"
      :rules="rules"
      :disabled="dialogData.isView"
      :model="dialogData.itemInfo"
      label-width="120px"
      label-suffix=" :"
    >
      <el-form-item>
        <el-checkbox v-model="dialogData.itemInfo.flagSelf" label="为本公司招聘" true-label="Y" false-label="N" />
      </el-form-item>
      <el-form-item label="客户公司名称" v-show="dialogData.itemInfo.flagSelf == 'N'">
        <el-select
          v-if="dialogData.optType == OptEnum.CREATE || dialogData.optType == OptEnum.EDIT"
          size="large"
          v-model="dialogData.itemInfo.jobCompanyId"
          placeholder="请选择公司"
          style="width: 100%"
          filterable
        >
          <el-option v-for="item in companies" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-input
          v-if="dialogData.optType == OptEnum.VIEW"
          size="large"
          placeholder="请输入"
          v-model="dialogData.itemInfo.jobCompanyName"
          show-word-limit
        />
      </el-form-item>
      <el-form-item label="职位名称" prop="title">
        <el-input size="large" placeholder="请输入职位名称" v-model="dialogData.itemInfo.title" maxlength="12" show-word-limit />
      </el-form-item>
      <el-form-item label="职位类型">
        <el-select
          v-model="dialogData.itemInfo.jobType"
          placeholder="请选择职位类型"
          size="large"
          style="width: 100%"
        >
          <el-option
            v-for="item in jobTypeEnum"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="职位类别" prop="jobTypeId">
        <el-tree-select
          v-model="dialogData.itemInfo.jobTypeId"
          :data="dialogData.jobTypes"
          check-strictly
          :render-after-expand="false"
          placeholder="请选择职位类别"
          style="width: 100%"
        ></el-tree-select>
      </el-form-item>
      <el-form-item label="职位描述" style="align-items: flex-start">
        <!-- <el-input
          style="width: 100%"
          v-model="dialogData.itemInfo.content"
          :autosize="{ minRows: 6 }"
          type="textarea"
          placeholder="请填写职位描述"
          maxlength="1000"
          show-word-limit
        /> -->
        <WangEditor height="200px" v-model:value="dialogData.itemInfo.content" />
      </el-form-item>
      <el-form-item label="职位福利">
        <el-select
          size="large"
          style="width: 100%"
          v-model="dialogData.itemInfo.tags"
          multiple
          multiple-limit="5"
          placeholder="请选择福利"
        >
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="其它福利">
        <div class="custom-wrapper">
          <el-tag
            v-for="tag in dynamicTags"
            :key="tag"
            class="mx-1"
            closable
            :disable-transitions="false"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            placeholder="请填写"
            ref="InputRef"
            v-model="inputValue"
            class="mx-1 w-20"
            size="small"
            maxlength="4"
            show-word-limit
            @keyup.enter="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button v-else class="mx-1" size="small" @click="showInput"> + 自定义福利 </el-button>
        </div>
      </el-form-item>
      <el-row :gutter="20">
        <el-col :span="14">
          <el-form-item label="招聘数量">
            <el-input-number
              size="large"
              style="width: 100%; text-align: left"
              placeholder="请输入招聘人数"
              v-model="dialogData.itemInfo.needCnt"
            />
          </el-form-item>
          <el-form-item label="综合薪资">
            <el-input
              size="large"
              style="width: 15%; text-align: left"
              :controls="false"
              placeholder="请输入最低薪"
              v-model="dialogData.itemInfo.priceStart"
              maxlength="8"
            />
            <span style="margin: 0 1rem; color: #ababab">至</span>
            <el-input
              size="large"
              style="width: 15%; text-align: left"
              :controls="false"
              placeholder="请输入最高薪"
              v-model="dialogData.itemInfo.priceEnd"
              maxlength="8"
            />
            <span style="margin-left: 1rem; margin-right: 1rem; color: #ababab">元/月</span>
            <el-checkbox v-model="dialogData.itemInfo.flagTalk" label="面议" true-label="Y" false-label="N" />
          </el-form-item>
          <el-form-item label="联系人" prop="contactor">
            <el-input
              placeholder="请填写联系人"
              v-model="dialogData.itemInfo.contactor"
              size="large"
              maxlength="15"
              show-word-limit
              disabled
            />
          </el-form-item>
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input
              placeholder="请填写联系人电话"
              v-model="dialogData.itemInfo.contactPhone"
              size="large"
              maxlength="15"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="学历要求">
            <el-select
              style="width: 100%"
              v-model="dialogData.itemInfo.requireEdu"
              class="m-2"
              placeholder="请选择学历要求"
              size="large"
            >
              <el-option v-for="item in degrees" :label="item.label" :value="item.value" :key="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="工作年限">
            <el-select
              style="width: 100%"
              v-model="dialogData.itemInfo.requireYear"
              class="m-2"
              placeholder="请选择工作年限要求"
              size="large"
            >
              <el-option v-for="item in workYears" :label="item.label" :value="item.value" :key="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="dialogData.itemInfo.flagCripple" label="可接受残疾人" true-label="Y" false-label="N" />
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="dialogData.itemInfo.flagOnlyCripple" label="只招聘残疾人" true-label="Y" false-label="N" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="14">
          <section class="form-s2" style="padding-top: 1rem; align-items: flex-start">
            <h2 style="margin: 1rem; margin-top: 0; margin-left: 2rem">发布地址</h2>
            <div class="address-option-box" v-if="dialogData.optType == OptEnum.CREATE">
              <el-select style="width: 168px" placeholder="请选择省" v-model="province_id">
                <el-option v-for="(p, i1) in provinces" :key="i1" :label="p.label" :value="p.value" />
              </el-select>
              <el-select style="width: 168px; margin-left: 10px" placeholder="请选择市" v-model="city_id">
                <el-option v-for="(c, i2) in citys" :key="i2" :label="c.label" :value="c.value" />
              </el-select>

              <!-- <el-button
                style="margin-left: 1rem; height: 30px"
                type="primary"
                @click="addPubAddress"
              >
                +&nbsp;添加发布地址
              </el-button> -->
            </div>
            <!-- <div
              class="address-option-box"
              v-if="dialogData.optType == OptEnum.CREATE"
            >
              <el-select
                style="flex: 1"
                placeholder="请选择地区"
                v-model="areaIds"
                multiple
              >
                <el-option
                  v-for="(a, i3) in areas"
                  :key="i3"
                  :label="a.label"
                  :value="a.value"
                />
              </el-select>
            </div> -->
            <div class="address-option-box" v-if="dialogData.pubFree && dialogData.pubFree.freeCnt">
              <el-alert
                :title="`当家可以使用免费发布 ${dialogData.pubFree.freeCnt} 个区域`"
                type="success"
                :closable="false"
                show-icon
              />
            </div>
            <div class="address-table-content">
              <el-table
                ref="multipleTableRef"
                style="width: 98%"
                max-height="300"
                v-if="dialogData.itemInfo.allpubtos.length"
                :data="dialogData.itemInfo.allpubtos"
                @selection-change="handleSelectionChange"
                border
              >
                <!-- <el-table-column
                  fixed="left"
                  label="#"
                  width="60"
                  align="center"
                >
                  <template #default="scope">
                    <el-checkbox v-model="scope.row.flagSelect"></el-checkbox>
                  </template>
                </el-table-column> -->
                <el-table-column type="selection" width="40" />
                <el-table-column prop="provinceName" label="省" align="center" />
                <el-table-column prop="cityName" label="市" align="center" />
                <el-table-column prop="areaName" label="区" align="center" />
                <el-table-column prop="showFee" label="费用" width="100" align="center" />
                <!-- <el-table-column label="免费">
                  <template #default="scope">
                    <el-switch
                      v-model="scope.row.flagFree"
                      :active-value="sysEnum.ACTIVE"
                      :inactive-value="sysEnum.INACTIVE"
                    />
                  </template>
                </el-table-column> -->
                <!-- <el-table-column
                  fixed="right"
                  label="操作"
                  width="120"
                  align="center"
                >
                  <template #default="scope">
                    <el-button
                      @click="handleRemovePubAddress(scope.$index)"
                      type="danger"
                      size="small"
                    >
                      移除
                    </el-button>
                  </template>
                </el-table-column> -->
              </el-table>
            </div>
          </section>
        </el-col>
        <el-col :span="10">
          <section class="form-s2" style="padding-top: 1rem">
            <div class="file-upload-label"><span>上传岗位照片/视频</span></div>
            <section class="file-upload-box">
              <UploadImgs
                v-model:fileList="dialogData.fileList"
                :disabled="dialogData.isView"
                :file-size="3"
                width="160px"
                height="160px"
                :api="uploadJob"
              >
                <template #tip> 大小不能超过 3M </template>
              </UploadImgs>
            </section>
          </section>
        </el-col>
      </el-row>

      <section class="form-s2" style="align-items: flex-start">
        <h2 style="margin: 1rem; margin-top: 0; margin-left: 2rem">工作地址</h2>
        <div v-if="jobAddressStr.length" class="jobaddress-marker-tip">
          <div class="addr-tag-content">
            <el-icon style="margin-right: 0.25rem" size="24">
              <Place />
            </el-icon>
            工作地址-{{ jobAddressStr }}
            <el-icon class="addr-close" @click="handleRemoveMarkJobAddress">
              <CircleClose />
            </el-icon>
          </div>
        </div>
        <div class="map-search-box">
          <el-input v-model="mapAddressQuery" placeholder="请输入地址查询" :prefix-icon="Search" @keyup.enter="queryCoord" />
          <el-button @click="queryCoord" type="primary" :icon="Search">查找</el-button>
          <el-button @click="handleMarkJobAddress" type="primary" :icon="Check">记为工作地址</el-button>
        </div>

        <div id="mcontainer" class="map-box"></div>
      </section>
    </el-form>

    <template #footer>
      <el-button @click="handleOffline" v-show="!dialogData.isView">下架</el-button>
      <el-input
        v-model="refuseContent"
        v-show="dialogData.isView"
        placeholder="请填写拒绝原因"
        :prefix-icon="EditPen"
        style="width: 260px; margin-left: 10px"
      />
      <el-button size="large" type="danger" @click="handleAduitFail" v-show="dialogData.isView">拒绝</el-button>
      <el-button size="large" type="success" @click="handleAduitPass" v-show="dialogData.isView">通过</el-button>
      <el-button size="large" type="primary" @click="handleLoadNext" v-show="dialogData.isView">审核下一个</el-button>
      <el-button @click="dialogVisible = false">关闭</el-button>
      <el-button size="large" type="primary" v-show="!dialogData.isView" @click="handleSubmit" :loading="btnLoading">
        确认发布
      </el-button>
      <!-- <el-button @click="handleOutput">输出</el-button> -->
      <el-divider />
      <div class="jobstatus-wrapper" v-show="dialogData.isView">
        <el-alert
          :title="`岗位状态 &nbsp;:&nbsp; ${filterEnum(dialogData.itemInfo.status, jobStatusType)}`"
          type="info"
          show-icon
          :closable="false"
        />
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, onMounted, shallowRef, nextTick } from "vue";
import { ElInput, ElMessage, ElTable, FormInstance } from "element-plus";
import { getOptTitle, OptEnum } from "@/biz/eenum/appEnum";
import { DialogParam } from "@/biz/interface/DialogType";
import { JobEntity } from "@/biz/interface/jobType";
import { getJobInfoApi, savePostApi } from "@/api/modules/sysjob/job";
import { getJobTagDropsByTypeVoListApi } from "@/api/modules/sysjob/jobtag";
import { getCompanyDropApi } from "@/api/modules/cpy/client";
// import Uploader from "@/components/Uploader/index.vue";
import { degrees, workYears } from "@/biz/datas/formDrops";
import { Search, Place, Check, CircleClose, EditPen } from "@element-plus/icons-vue";
import { CommonTree } from "@/biz/interface";
import { getJobTypesTreeApi } from "@/api/modules/sysjob/tp";
import { getCoordFromAddress, getAddressFromCoord } from "@/api/modules/common/map";
import UploadImgs from "@/components/Upload/ImgMultiple.vue";
import AMapLoader from "@amap/amap-jsapi-loader";
import { useAddress } from "@/biz/hooks/useAddress";
import { getAreafeeCntApi, getAreafeesApi, setJobOffline } from "@/api/modules/cpyjob/ft";
import { uploadJob } from "@/api/modules/upload";
import { useHandleData } from "@/hooks/useHandleData";
import WangEditor from "@/components/WangEditor/index.vue";
import { auditFailApi, auditPassApi, getNextJobApi } from "@/api/modules/sysjob/job";
import { jobStatusType, jobTypeEnum } from "@/biz/datas/jobData";
import { filterEnum } from "@/utils";
import { useAppStore } from "@/stores/modules/app";
import { getAreaTreeApi } from "@/api/modules/common/address";

const multipleTableRef = ref<InstanceType<typeof ElTable>>();

const appStore = useAppStore();

const { provinces, citys, areas, province_id, city_id } = useAddress();

// const fileList = ref([
//   // {
//   //   name: "1",
//   //   url: "https://iamge-1259297738.cos.ap-chengdu.myqcloud.com/img/20220728110013.jpg",
//   // },
//   // {
//   //   name: 2,
//   //   url: "https://qwzls.oss-cn-hangzhou.aliyuncs.com/pub/361641557994115072.jpeg",
//   // },
// ]);

const areaIds = ref([]);
const jobAddressStr = ref("");
const jobAddressObject = ref({} as any);
const multipleSelection = ref<any[]>([]);

// const handleRemovePubAddress = (index: number) => {
//   dialogData.itemInfo.pubtos.splice(index, 1);
// };

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
};

const addPubAddress = async () => {
  if (areaIds.value && areaIds.value.length) {
    dialogData.itemInfo.allpubtos = [];
    let res = await getAreafeesApi({ areaIds: areaIds.value });
    if (res) {
      console.log("接收到的收费信息", res);
      // dialogData.itemInfo.pubtos = res.data as unknown as [];
      dialogData.itemInfo.allpubtos = res.data as unknown as [];
    }
  } else {
    ElMessage.error("请选择正确的地址！");
  }
};

// 每当选择市后，区域发生变化，自动把所有的区域加到默认发布
const autoAddAllAreas = () => {
  if (areas.value && areas.value.length) {
    // console.log("当前的区域数据", areas.value);
    areaIds.value = [];
    areas.value.forEach(item => {
      if (item.value) {
        areaIds.value.push(item.value);
      }
    });

    addPubAddress();
  }
};

interface PostDialogOption extends DialogParam {
  //弹出表单的标题
  title: string;
  // 是否是查看状态，查看状态是不可以提交数据
  isView: boolean;
  // 图片
  fileList: [];
  //查找的地址坐标
  addressLocation: string;
  // 可免费发布的信息
  pubFree: { freeCnt?: number };
  // 岗位类型树
  jobTypes: CommonTree[];
  //当前的数据对象
  itemInfo: JobEntity;
}

//提交按钮，避免多次提交
const btnLoading = ref(false);
//弹出框的参数
const dialogVisible = ref(false);
//当前表单数据在这里初始化
const dialogData = reactive<PostDialogOption>({
  optType: OptEnum.UNKNOW,
  title: "",
  isView: false,
  fileList: [],
  addressLocation: "",
  pubFree: {},
  jobTypes: [],
  itemInfo: {
    // * 标题
    title: "",
    //岗位的企业
    jobCompanyId: "",
    // * 类型
    jobTypeId: undefined,
    // * 招聘人数
    needCnt: 0,
    // * 价格开始
    priceStart: 2000,
    // * 价格结束
    priceEnd: 5000,
    // * 价格面议
    flagTalk: "N",
    // * 职位描述
    content: "",
    // * 学历要求
    requireEdu: "",
    // * 工作年限
    requireYear: "",
    // * 可接受
    flagCripple: "N",
    // * 只接受
    flagOnlyCripple: "N",
    // * 联系人
    contactor: "",
    // * 联系电话
    contactPhone: "",
    // * 公开电话标识
    flagShowPhone: "",
    // * 位置
    jobAddressId: "",
    jobAddress: {},
    // *  职位福利
    tags: [],
    // * 发布地区,省市一个，地区多个
    allpubtos: [],
    pubtos: [],
    // *  图片
    imgs: [],
    // *  视频
    vdos: [],
    // * 上传的资源，把图片和视频先合在一起维护
    reses: []
  }
});

const map = shallowRef(null);
const amap = shallowRef(null);
const mapConfig = {
  key: "32e88e4ed5ea47ee273ea5c3bb8d7a4a",
  version: "2.0",
  plugins: ["AMap.DistrictSearch"]
};
const mapInitInfo = {
  viewMode: "2D",
  zoom: 12,
  center: [105.602725, 37.076636]
};
 
const initMap = () => {
  // 这个可以不加
  // window._AMapSecurityConfig = {
  //     securityJsCode: "a302f8d7dafa9da498400f0aab82c5fa",
  // };
  AMapLoader.load(mapConfig)
    .then(AMap => {
      map.value = new AMap.Map("mcontainer", mapInitInfo);
      amap.value = AMap;
      // map.value.add(new AMap.Marker({
      //   position: new AMap.LngLat(121.550357,29.874556)
      // }))
    })
    .catch(e => console.log(e));
};

const options = ref([] as any);
const companies = ref([] as any);
// const imgUploader = ref<InstanceType<typeof Uploader>>();
// const videoUploader = ref<InstanceType<typeof Uploader>>();

const inputValue = ref("");
const dynamicTags = ref([]);
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();

const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

const handleInputConfirm = () => {
  if (inputValue.value) {
    if (dynamicTags.value && dynamicTags.value.length > 2) {
      ElMessage.error({ message: `最多可添加3个自定义福利.` });
      return;
    }
    dynamicTags.value.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};

// 不用默认的 10
const getJobTagsByTypeVoList = (params: { type: number }): void => {
  getJobTagDropsByTypeVoListApi(params).then(res => {
    // console.log(res);
    options.value = res.data || [];
  });
};

getCompanyDropApi({}).then(res => {
  companies.value = res.data;
});

// 接收父组件传过来的参数
const acceptParams = (params: DialogParam): void => {
  dialogData.optType = params.optType;
  dialogData.rowData = params.rowData;
  dialogData.isView = dialogData.optType === OptEnum.VIEW;
  dialogData.title = getOptTitle(dialogData.optType);

  if (dialogData.optType === OptEnum.CREATE) {
    initItemInfo();
  } else if (dialogData.rowData && dialogData.rowData.id) {
    getItemInfo(dialogData.rowData.id);
  }

  dialogVisible.value = true;
};

//初始化页面的数据
const initItemInfo = (): void => {
  dialogData.itemInfo = {
    // * 标题
    title: "",
    //岗位的企业
    jobCompanyId: "",
    // * 类型
    jobTypeId: undefined,
    // * 招聘人数
    needCnt: 0,
    // * 价格开始
    priceStart: 2000,
    // * 价格结束
    priceEnd: 5000,
    // * 价格面议
    flagTalk: "N",
    flagSelf: "N",
    // * 职位描述
    content: "",
    // * 学历要求
    requireEdu: "",
    // * 工作年限
    requireYear: "",
    // * 可接受
    flagCripple: "N",
    // * 只接受
    flagOnlyCripple: "N",
    // * 联系人
    contactor: "",
    // * 联系电话
    contactPhone: "",
    // * 公开电话标识
    flagShowPhone: "",
    // * 位置
    jobAddressId: "",
    // *  职位福利
    tags: [],
    // * 发布地区,省市一个，地区多个
    jobAddress: {},
    allpubtos: [],
    pubtos: [],
    // *  图片
    imgs: [],
    // *  视频
    vdos: [],
    reses: []
  };
  // 默认当前人
  dialogData.itemInfo.contactor = appStore.userName || "";
  dialogData.itemInfo.contactPhone = appStore.userPhone || "";
  dialogData.fileList = [];
  handleRemoveMarkJobAddress();
};
//获取当前数据的详情，直接调用接口获取数据
const getItemInfo = async (id: string) => {
  if (id) {
    let { data } = await getJobInfoApi({ id });
    dialogData.itemInfo = data as unknown as JobEntity;

    // console.log("获取当前岗位信息：", dialogData.itemInfo);
    dialogData.itemInfo.allpubtos = [];
    if (data && data?.pubtos && data?.pubtos.length > 0) {
      // 先获取所有的信息
      const dataAreas = await getAreaTreeApi({
        cityId: data.pubtos[0].cityId!
      });
      // console.log("CityID获取的所有区域", dataAreas);
      if (dataAreas && dataAreas.data) {
        // console.log("当前的区域数据", areas.value);
        areaIds.value = [];
        dataAreas.data.forEach(item => {
          if (item.value) {
            areaIds.value.push(item.value);
          }
        });
        await addPubAddress();
      }
    }

    const rows = multipleTableRef.value?.data;
    if (rows) {
      rows.forEach(row => {
        // console.log("当前行的数据:", row);
        let selected = false;
        if (dialogData.itemInfo.pubtos) {
          selected = dialogData.itemInfo.pubtos.some(item => item.areaId == row.areaId);
        }
        multipleTableRef.value!.toggleRowSelection(row, selected);
      });
    }

    if (dialogData.itemInfo.customTags) {
      dynamicTags.value = dialogData.itemInfo.customTags.split(",");
    } else {
      dynamicTags.value = [];
    }

    if (dialogData.itemInfo.jobAddress) {
      jobAddressStr.value =
        (dialogData.itemInfo.jobAddress.provinceName || "") +
        (dialogData.itemInfo.jobAddress.cityName || "") +
        (dialogData.itemInfo.jobAddress.districtName || "") +
        (dialogData.itemInfo.jobAddress.address || "");
    } else {
      jobAddressStr.value = "";
    }

    // 加了下面这个就不出数据了。 虽然有数据，去掉就不会停的多加出现
    // dialogData.fileList = [];
    dialogData.fileList.length = 0;
    let imgIdx = 1;
    if (dialogData.itemInfo.imgs) {
      dialogData.itemInfo.imgs.forEach(img => {
        dialogData.fileList.push({ name: imgIdx, url: img });
        imgIdx = imgIdx + 1;
      });
    }
    if (dialogData.itemInfo.vdos) {
      dialogData.itemInfo.vdos.forEach(vdo => {
        dialogData.fileList.push({ name: imgIdx, url: vdo });
        imgIdx = imgIdx + 1;
      });
    }

    // console.log(dialogData.fileList);
  }
};

const getNextItemInfo = async (id: string) => {
  if (id) {
    let { data } = await getNextJobApi({ id });
    if (data) {
      dialogData.itemInfo = data as unknown as JobEntity;

      dialogData.itemInfo.allpubtos = [];
      if (data && data?.pubtos && data?.pubtos.length > 0) {
        // 先获取所有的信息
        const dataAreas = await getAreaTreeApi({
          cityId: data.pubtos[0].cityId!
        });
        // console.log("CityID获取的所有区域", dataAreas);
        if (dataAreas && dataAreas.data) {
          // console.log("当前的区域数据", areas.value);
          areaIds.value = [];
          dataAreas.data.forEach(item => {
            if (item.value) {
              areaIds.value.push(item.value);
            }
          });
          await addPubAddress();
        }
      }

      const rows = multipleTableRef.value?.data;
      if (rows) {
        rows.forEach(row => {
          // console.log("当前行的数据:", row);
          let selected = false;
          if (dialogData.itemInfo.pubtos) {
            selected = dialogData.itemInfo.pubtos.some(item => item.areaId == row.areaId);
          }
          multipleTableRef.value!.toggleRowSelection(row, selected);
        });
      }

      if (dialogData.itemInfo.jobAddress) {
        jobAddressStr.value =
          (dialogData.itemInfo.jobAddress.provinceName || "") +
          (dialogData.itemInfo.jobAddress.cityName || "") +
          (dialogData.itemInfo.jobAddress.districtName || "") +
          (dialogData.itemInfo.jobAddress.address || "");
      } else {
        jobAddressStr.value = "";
      }

      // 加了下面这个就不出数据了。 虽然有数据，去掉就不会停的多加出现
      // dialogData.fileList = [];
      dialogData.fileList.length = 0;
      let imgIdx = 1;
      if (dialogData.itemInfo.imgs) {
        dialogData.itemInfo.imgs.forEach(img => {
          dialogData.fileList.push({ name: imgIdx, url: img });
          imgIdx = imgIdx + 1;
        });
      }
      if (dialogData.itemInfo.vdos) {
        dialogData.itemInfo.vdos.forEach(vdo => {
          dialogData.fileList.push({ name: imgIdx, url: vdo });
          imgIdx = imgIdx + 1;
        });
      }
    } else {
      ElMessage.success("没有待审核数据了.");
    }
  }
};

//下架
const handleOffline = async () => {
  if (dialogData.rowData && dialogData.rowData.id) {
    let res = await useHandleData(setJobOffline, { id: dialogData.rowData.id }, `【${dialogData.itemInfo.title}】,确认下架?`);

    if (res) {
      //刷新列表数据
      emits("refresh-list");
      dialogVisible.value = false;
    }
  }
};

//数据较验
const rules = reactive({
  title: [{ required: true, message: "请填写职位名称", trigger: "blur" }],
  content: [{ required: true, message: "请填写岗位内容", trigger: "blur" }],
  jobTypeId: [{ required: true, message: "请选择岗位类型", trigger: "change" }],
  contactor: [{ required: true, message: "请填写联系人", trigger: "blur" }],
  contactPhone: [{ required: true, message: "请填写联系电话", trigger: "blur" }]
});

// 提交数据（新增/编辑）
const jobFormRef = ref<FormInstance>();
const handleSubmit = () => {
  // console.log("当前选择的区域", multipleSelection.value);

  if (multipleSelection.value && multipleSelection.value.length == 0) {
    ElMessage.error({ message: `请选择发布区域！` });
  }

  btnLoading.value = true;
  jobFormRef.value!.validate(async valid => {
    if (!valid) {
      btnLoading.value = false;
      return;
    }
    try {
      if (dialogData.optType === OptEnum.CREATE || dialogData.optType === OptEnum.EDIT) {
        if (dialogData.fileList) {
          dialogData.itemInfo.imgs = [];
          dialogData.itemInfo.vdos = [];
          dialogData.itemInfo.reses = [];
          dialogData.fileList.forEach(file => {
            // console.log("每个文件, ", file, file.url);
            if (file && file.url) {
              dialogData.itemInfo.reses.push(file.url);
            }
          });
        }

        // 填充发布区域
        dialogData.itemInfo.pubtos = multipleSelection.value;

        // 填充自定义标签
        dialogData.itemInfo.customTags = "";
        if (dynamicTags.value && dynamicTags.value.length > 0) {
          dialogData.itemInfo.customTags = dynamicTags.value.join(",");
        }

        //提交数据
        let res = await savePostApi({
          ...dialogData.itemInfo
        });
        if (res.data) {
          ElMessage.success({ message: `${dialogData.title}工作成功！` });
          //刷新列表数据
          emits("refresh-list");
          dialogVisible.value = false;
        }
      }
    } catch (error) {
      console.log("出现异常情况,", error);
    } finally {
      btnLoading.value = false;
    }
  });
};

// 审核不通过
const refuseContent = ref("");
const handleAduitFail = async () => {
  if (dialogData.itemInfo && dialogData.itemInfo.id) {
    await useHandleData(
      auditFailApi,
      { id: dialogData.itemInfo.id!, refuseCtn: refuseContent.value || "" },
      `【${dialogData.itemInfo.title}】岗位，审核不通过`
    );
  }
};

// 审核通过
const handleAduitPass = async () => {
  if (dialogData.itemInfo && dialogData.itemInfo.id) {
    await auditPassApi({
      id: dialogData.itemInfo.id
    }).then(res => {
      if (res.data) {
        ElMessage.success("审核通过");
      }
    });
  }
};

// 加载下一个
const handleLoadNext = () => {
  // getNextJobApi;
  console.log("加载下一个");
  if (dialogData.itemInfo && dialogData.itemInfo.id) {
    getNextItemInfo(dialogData.itemInfo.id);
  }
};

//初始化一些参数
onMounted(() => {
  getJobTypesTreeApi({}).then(res => {
    dialogData.jobTypes = res.data as unknown as CommonTree[];
  });
  getAreafeeCntApi({}).then(res => {
    dialogData.pubFree = res.data as unknown as {};
  });
  getJobTagsByTypeVoList({ type: 1 });
});

watch(dialogVisible, n => {
  if (n) {
    initMap();
  }
});

watch(areas, n => {
  if (n) {
    autoAddAllAreas();
  }
});

const mapAddressQuery = ref("");

const handleMarkJobAddress = () => {
  if (Object.keys(jobAddressObject.value).length > 0) {
    jobAddressStr.value =
      jobAddressObject.value.addressComponent.province +
      jobAddressObject.value.addressComponent.city +
      jobAddressObject.value.addressComponent.district +
      mapAddressQuery.value;
    //格式化需要的数据

    if (jobAddressObject.value.addressComponent.district) {
      //需要到区，不然数据保存不上
      dialogData.itemInfo.jobAddress = {
        provinceName: jobAddressObject.value.addressComponent.province,
        cityName: jobAddressObject.value.addressComponent.city,
        areaName: jobAddressObject.value.addressComponent.district,
        location: dialogData.addressLocation,
        address: mapAddressQuery.value
      };

      // 如果areaName 不是字符串的时候，设置为空 地图返回了一个空的数组，参数异常。
      if(dialogData.itemInfo.jobAddress){
        if( typeof dialogData.itemInfo.jobAddress.areaName !== 'string'){
          // 设置为空
          dialogData.itemInfo.jobAddress.areaName="";
        }
      }
    } else {
      ElMessage.error("选择的位置需要精确到区域.");
    }
  } else {
    ElMessage.error("请先进行地址查询！");
  }
};

const handleRemoveMarkJobAddress = () => {
  dialogData.itemInfo.jobAddress = {};
  // jobAddressObject.value = {}
  jobAddressStr.value = "";
};

const queryCoord = () => {
  getCoordFromAddress(mapAddressQuery.value)
    .then(res => res.json())
    .then((res: any) => {
      // const markerClick = (e:any) => {
      //   console.log(e)
      // }
      // jobAddressObject.value = res.geocodes[0];
      dialogData.addressLocation = res.geocodes[0].location;
      getAddressFromCoord(res.geocodes[0].location)
        .then(address => address.json())
        .then((ares: any) => {
          jobAddressObject.value = ares.regeocode;
          // console.log(jobAddressObject.value)
        });
      res.geocodes.forEach((geo: any, idx: number) => {
        let coord = geo.location.split(",").map((e: string) => parseFloat(e));
        if (idx == 0) {
          map.value!.setCenter(coord);
        }
        let marker = new amap.value!.Marker({
          position: new amap.value!.LngLat(coord[0], coord[1]),
          title: geo.formatted_address,
          draggable: true,
          cursor: "move"
        });
        // marker.on('click', markerClick)
        map.value!.add(marker);
      });
    });
};

//页面事件
const emits = defineEmits(["refresh-list"]);

//页面参数
defineExpose({
  acceptParams
});
</script>

<style lang="scss" scoped>
.post-dialog-content {
  background-color: #f7f7f7;
  box-sizing: border-box;
  padding: 1rem;
  .el-form-item {
    width: calc(100% - 3rem);
    margin: 0;
    margin-bottom: 1rem;
    display: flex;
    align-items: center;
  }
}
.form-s1 {
  // border: 1px solid green;
  background-color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: left;
  padding: 2rem 0 1rem 0;
  border-radius: 0.25rem;
}
.form-s2 {
  // border: 1px solid blue;
  @extend .form-s1;
  margin-top: 1rem;
}
#base-number-box {
  display: flex;
  width: 100%;
  flex-wrap: wrap;
  flex-direction: row;
  .el-form-item {
    width: 20rem;
    margin-top: 0.5rem;
  }
}
.file-upload-label {
  width: 100%;
  color: rgb(49, 49, 49);
  font-weight: bold;
  font-size: large;
  display: flex;
  justify-content: flex-start;
  margin-bottom: 1rem;
  padding-left: 4rem;
}
.file-upload-box {
  padding-left: 4rem;
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: flex-start;
}
#mcontainer {
  width: 90%;
  top: -3.5rem;
  height: 26rem;
  margin-left: 2rem;
  margin-bottom: 1rem;
  border-radius: 4px;
}
.address-table-box {
  border: 1px solid red;
  width: 100%;
  padding: 2rem;
  position: relative;
  top: -5rem;
  & h2 {
    margin-top: 0.5rem;
    margin-bottom: 1rem;
  }
}
.address-option-box {
  // border: 1px solid red;
  box-sizing: border-box;
  margin-bottom: 0.25rem;
  padding: 0 10px;
  width: 100%;
  display: flex;
  align-items: center;
}

.address-table-content {
  margin-top: 1rem;
  box-sizing: border-box;
  padding: 0 10px;
  width: 100%;
  display: flex;
  align-items: center;
}
.jobaddress-marker-tip {
  margin-left: 2rem;
  margin-bottom: 0.5rem;
}
.addr-tag-content {
  display: flex;
  align-items: center;
  color: rgb(117, 117, 117);
  font-size: 1.125rem;
  font-weight: bold;
  padding: 0.45rem;
  border: 1px solid white;
  border-radius: 4px;
  & .el-icon {
    font-size: 1.4rem;
    color: red;
  }
  cursor: default;
  & .addr-close {
    visibility: hidden;
    color: rgb(161, 161, 161);
    margin-left: 0.25rem;
    font-size: 1.125rem;
    cursor: pointer;
    &:hover {
      color: rgb(114, 114, 114);
    }
  }
  &:hover .addr-close {
    visibility: visible;
  }
  &:hover {
    border: 1px solid rgb(221, 221, 221);
    border-radius: 4px;
  }
}

.map-search-box {
  z-index: 100;
  width: 60%;
  // border: 1px solid red;
  display: flex;
  transform: translateY(20px);
  margin-left: 40px;
}

.map-box {
  // border: 1px solid green;
  transform: translateY(30px);
}

.jobstatus-wrapper {
  // border: 1px solid red;
  margin-bottom: 5px;
  font-size: 1.2em;
  color: var(--el-color-primary);
  font-weight: 600;
}

.custom-wrapper {
  border: 1px solid var(--el-color-info-light-7);
  width: 100%;
  height: 40px;
  line-height: 40px;
  border-radius: 4px;

  .mx-1 {
    margin: 0 5px;
  }

  .w-20 {
    width: 200px;
  }
}
</style>
